﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleTest
{
    public class Program
    {
        static int[] intArrTemp = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        static List<int> intListTemp = Enumerable.Range(0, 1000).ToList();
        static int index = 0;
        static bool hasLock = true;
        static Object Lock = new Object();
        static void Main(string[] args)
        {
            Task.Run(() => { Test01(intListTemp, ref index); });
            Task.Run(() => { Test02(intListTemp, ref index); });
            Console.ReadLine();
        }

        static void Test01(List<int> arrInt, ref int index)
        {
            Monitor.Enter(Lock);
            if (index == 1000)
            {
                return;
            }
            Console.WriteLine(arrInt[index]);
            index = (index + 1);
            hasLock = true;
            Console.WriteLine($"当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
            Monitor.Exit(Lock);
            Test01(arrInt, ref index);
        }
        static void Test02(List<int> arrInt, ref int index)
        {
            Monitor.Enter(Lock);
            if (index == 1000)
            {
                return;
            }
            Console.WriteLine(arrInt[index]);
            index = (index + 1);
            hasLock = true;
            Console.WriteLine($"当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
            Monitor.Exit(Lock);
            Test02(arrInt, ref index);
        }
    }
}
